package com.hakim.wfb.schedule.task;

import com.hkfs.fundamental.spring.utils.SpringContextUtils;
import com.hkfs.fundamental.zookeeper.ZooKeeperClient;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;


/**
 */
public abstract class BaseTask {

    private Logger logger = LoggerFactory.getLogger(BaseTask.class);

    public abstract void execute();

    public void doTask() {

        String clazzName = this.getClass().getSimpleName();
        String className = clazzName.substring(0, 1).toLowerCase() + clazzName.substring(1);
        String lockPath = "/cinema/schedule/" + className + "/lock";

        ZooKeeperClient zkClient = (ZooKeeperClient) SpringContextUtils.getBean("zkClient");
        CronTriggerImpl cronTrigger = (CronTriggerImpl) SpringContextUtils.getBean(className.replace("Task", "Job") + "CronTrigger");

        logger.info("lock path:{},zkClient:{},trigger cron:{}", lockPath, zkClient, cronTrigger.getCronExpression());

        Boolean isGetLocker = false;
        InterProcessMutex lock = new InterProcessMutex(zkClient.getClient(), lockPath);
        try {
            if (lock.acquire(2000, TimeUnit.MILLISECONDS)) {
                isGetLocker = true;
                execute();
            }
        } catch (Exception e) {
            logger.error("BaseTask 执行锁任务时抛错：", e);
        } finally {
            try {
                if (isGetLocker) {
                    lock.release();
                }
            } catch (Exception e) {
                logger.error("释放锁出错", e);
            }
        }
    }
}
